package com.lnj.messages.consumer;

import com.lnj.bean.model.Orders;
import com.lnj.bean.model.User;
import com.lnj.messages.mapper.OrdersMapper;
import com.lnj.messages.mapper.ProductMapper;
import com.lnj.messages.mapper.UserMapper;
import com.lnj.messages.servise.OrderDelayService;
import com.lnj.messages.utiles.JsonUtil;
import com.lnj.messages.utiles.MailClientUtil;
import com.lnj.utils.OrderMessage;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class OrdersConsumer {
    @Autowired
    private OrderDelayService orderDelayService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private MailClientUtil mailClientUtil;
    @Autowired
    private JsonUtil jsonUtil;


    // 处理订单创建事件
    @KafkaListener(topics = "orders.created")
    public void consume(String orderMessage) {
        OrderMessage orderMessage1 = jsonUtil.fromJson(orderMessage, OrderMessage.class);
        log.info("orders.created消费消息: {}", orderMessage1);
        orderDelayService.handleOrderCreated(orderMessage1);
    }

    // 处理支付成功事件
    @KafkaListener(topics = "orders.paid")
    public void consumePaid(String orderMessage) {
        OrderMessage orderMessage1 = jsonUtil.fromJson(orderMessage, OrderMessage.class);
        log.info("orders.paid消费消息: {}", orderMessage1);
        try {
            orderDelayService.handleOrderPaid(orderMessage1);
        } catch (SchedulerException e) {
            log.error("处理支付成功事件失败", orderMessage1.getOrderId());
            throw new RuntimeException(e);
        }
    }

    // 处理订单提醒事件
    @KafkaListener(topics = "orders.reminded")
    public void consumeReminded(String orderMessage) {
        OrderMessage orderMessage1 = jsonUtil.fromJson(orderMessage, OrderMessage.class);
        log.info("orders.reminded消费消息: {}", orderMessage1);
        Long orderId = orderMessage1.getOrderId();
        // 从数据库中查询订单
        Orders orders = ordersMapper.selectById(orderId);
        //判断是否已经支付，支付了就跳过这个流程，查询订单消息
        if (orders == null) {
            log.error("订单不存在，orderId: {}", orderId);
            return;
        }
        if (orders.getOrderStatus() == 1) {
            Long userId = orders.getUserId();
            User user = userMapper.selectById(userId);
            if (user == null) {
                log.error("用户不存在，userId: {}", userId);
                return;
            }

            Map<String,Object> map=new HashMap<>();
            map.put("userName",user.getUserName());
            map.put("orderId",orderId);
            map.put("createTime",orders.getUpdateTime());
            LocalDateTime expireTime = orders.getUpdateTime().plusMinutes(15);
            map.put("expireTime", expireTime);
            map.put("payUrl","localhost:8080");

            mailClientUtil.sendTemplateMail(user.getEmail(),"提醒用户支付","userPay",map);
        }
    }

    // 处理订单取消事件
    @KafkaListener(topics = "orders.cancelled")
    public void consumeCancelled(String orderMessage) {
        OrderMessage orderMessage1 = jsonUtil.fromJson(orderMessage, OrderMessage.class);
        log.info("orders.cancelled消费消息: {}", orderMessage1);
        Long orderId = orderMessage1.getOrderId();
        // 从数据库中查询订单
        Orders orders = ordersMapper.selectById(orderId);
        if (orders == null) {
            log.error("订单不存在，orderId: {}", orderId);
            return;
        }
        if (orders.getOrderStatus() == 1) {
            //取消订单
            orders.setOrderStatus(0);
            orders.setUpdateTime(LocalDateTime.now()); // 更新操作时间
            ordersMapper.updateById(orders);
            log.info("订单 {} 已成功取消", orderId);
        }
    }
}
